import json
from urllib.request import Request, urlopen


class WechatNotifiy:
    _key = ""
    _send_api = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="
    _headers = {"Content-Type": "application/json"}

    """
    初始化，创建群机器人时获取key

    key: 群机器人key
    """

    def __init__(self, key="9988d51d-5f60-4064-bfd4-c137170cd071"):
        self._key = key

    """
    生成消息发送URL
    """

    def _get_notify_send_api(self):
        return "{}{}".format(self._send_api, self._key)

    """
    发送文本消息

    message: 要发送的文本内容
    atMobiles: 需at提醒的钉钉用户手机号列表
    isAtall: 是否at提醒所有群用户
    """

    def send_text(self, message, at_mobiles: list, is_at_all=False):
        if is_at_all:
            at_mobiles.append("@all")

        raw = {"msgtype": "text", "text": {"content": message, "mentioned_mobile_list": at_mobiles}}
        return self._send_message(raw)

    """
    发送MarkDown文本消息

    message: 要发送的文本内容
    atMobiles: 需at提醒的钉钉用户手机号列表
    isAtall: 是否at提醒所有群用户
    """

    def send_markdown(self, content, at_mobiles: list, is_at_all=False):
        if is_at_all:
            at_mobiles.append("@all")

        raw = {"msgtype": "markdown", "markdown": {"content": content, "mentioned_mobile_list": at_mobiles}}
        return self._send_message(raw)

    """
    消息体发送

    json_data: 所要发送的消息体
    """

    def _send_message(self, json_data):
        url = self._get_notify_send_api()
        data = bytes(json.dumps(json_data), "utf-8")
        request = Request(url, headers={"Content-Type": "application/json"}, data=data)
        response = urlopen(request)
        html = response.read().decode("utf-8")
        result = json.loads(html)

        return result['errcode'], result["errmsg"]

    def send_image_text(self, title, image_path, description):
        json_data = {
                "msgtype": "news",
                "news": {
                   "articles" : [
                       {
                           "title": title,
                           "description": description,
                           "url" : image_path,
                           "picurl" : image_path
                       }
                    ]
                }
            }
        return self._send_message(json_data)



